const fs = require("fs");
const path = require("path");
const qiniu = require("./qiniu");
const aliyun = require("./aliyun");
const axios = require("axios").default;
const uuid = require("uuid");
const process = require("process");
const filesize = require("filesize");
const Toolbox = require("./Toolbox");
const util = require("util")

/**
 *
 * @description 从七牛下载的速度 和上传7niu的速度   和 上传阿里云的速度
 * @param {String} tmp_dir
 * @param {string} target_file
 */
async function speed_test(target_file = "", tmp_dir = process.cwd()) {
  if (!target_file) {
    let resource_url = "https://qnimg.pianke.me/5794c29b9cc58331aa91b603baa59b4620181117.bin"
    let download_start = Date.now();
    console.log("download start...", resource_url)
    axios.get(resource_url, {
      responseType: "stream"
    }).then(async response => {
      let filename = uuid() + ".bin";
      let target_file_fullpath = path.join(tmp_dir, filename)
      response.data.pipe(fs.createWriteStream(target_file_fullpath));
      /**@type {ReadableStream} */
      let p = response.data;
      p.on("end", async () => {
        let download_end = Date.now();
        let stat = (await Toolbox.getStats(target_file_fullpath)).stats;
        console.log("file size is ", filesize(stat.size));
        let bytes_p_s = stat.size / ((download_end - download_start) / 1000);
        console.log("download speed is ", filesize(bytes_p_s) + "/s");
        let o_up7niuspeed = await (new qiniu.Pianke7Niu).getUploadSpeed(target_file_fullpath);
        console.log("qiniu upload", util.inspect(o_up7niuspeed))
        let o_upaliyunspeed = await (new aliyun.PiankeAliyun).getUploadSpeed(target_file_fullpath);
        console.log("aliyun upload", util.inspect(o_upaliyunspeed));
      })
    }).catch(axerr => {
      console.error("下载失败了", axerr);
    })
  }else{
    let o_up7niuspeed = await (new qiniu.Pianke7Niu).getUploadSpeed(target_file);
    console.log("qiniu upload", util.inspect(o_up7niuspeed))
    let o_upaliyunspeed = await (new aliyun.PiankeAliyun).getUploadSpeed(target_file);
    console.log("aliyun upload", util.inspect(o_upaliyunspeed));
  }
}




module.exports = {
  class_qiniu: qiniu.Pianke7Niu,
  class_aliyun: aliyun.PiankeAliyun,
  speed_test: speed_test
}